package com.hospital.tts;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.hospital.tts.adapter.MyAdapter;
import com.hospital.tts.base.BaseActivity;
import com.hospital.tts.dataBean.InfoBean;
import com.hospital.tts.dataBean.Person;
import com.hospital.tts.dataBean.UserBean;
import com.hospital.tts.sax.SAXForHandler;
import com.hospital.tts.sax.SAXInfoData;
import com.hospital.tts.xunfei.TtsDemo;
import com.hospital.tts.xunfei.TtsSettings;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvent;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.util.ResourceUtil;
import com.xubo.linescrollviewlib.LineScrollView;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class MainActivity extends BaseActivity {

    private RecyclerView recyclerView, recyclerView2;
    private List<InfoBean> guohao_list = new ArrayList<>();
    private TextView txt_day, tvWeek, tvTime;
    private LineScrollView linelist_lsv;
    List<String> lineList = new ArrayList<String>();
    List<String> lineList2 = new ArrayList<String>();

//    List<InfoBean> lineList = new ArrayList<InfoBean>();


    private String result;
    //定义获取手机信息的SoapAction与命名空间,作为常量
//    private static final String AddressnameSpace = "http://WebXml.com.cn/";
    //归属地查询相关参数
//    private static final String Addressurl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx"
//    private static final String Addressurl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl ";
//
//    private static final String Addressmethod = "getMobileCodeInfo";
//    private static final String AddresssoapAction = "http://WebXml.com.cn/getMobileCodeInfo";

    //定义获取手机信息的SoapAction与命名空间,作为常量
    private static final String AddressnameSpace = "http://tempurl.org";
    //归属地查询相关参数
    private static final String Addressurl = "https://pubh.hbkruan.com/anxin/soap?wsdl";

    private static final String Addressmethod = "uf_get_pid_zfxm";
    private static final String AddresssoapAction = "http://tempurl.org/uf_get_pid_zfxm";

    Timer timer = new Timer();
    String now_name = "", now_number = "", queue_id = "", old_queue_id = "0";
    TextView now_userName, now_userNumber;//正在就诊信息

    boolean is_data = false;
    boolean is_enpaly = true;
    MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        xunfeiinit();
        initView();
    }

    public void initView() {

        linelist_lsv = findViewById(R.id.linelist_lsv);
//        linelist_lsv.setLines(lineList);
//        linelist_lsv.clear();  //清除显示
//        linelist_lsv.addLine("----增加滚动行----");  //增加一行
//        linelist_lsv.setLines(lineList2);//设置数据
//        linelist_lsv.setLines(lineList);//设置数据

        recyclerView = (RecyclerView) findViewById(R.id.main_recycler_view1);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);//第二个参数为网格的列数
        recyclerView.setLayoutManager(gridLayoutManager);
         myAdapter = new MyAdapter(guohao_list, this);
        recyclerView.setAdapter(myAdapter);




        txt_day = (TextView) findViewById(R.id.txt_day);
        tvWeek = (TextView) findViewById(R.id.tvWeek);
        tvTime = (TextView) findViewById(R.id.tvTime);
        initRightTopView();

        tvTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    public void run() {
                        getland();
                    }
                }).start();

            }
        });
        now_userName = (TextView) findViewById(R.id.now_userName);
        now_userNumber = (TextView) findViewById(R.id.now_userNumber);


        ImageView img = (ImageView) findViewById(R.id.test);
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(MainActivity.this, TtsDemo.class);
//                startActivity(intent);
                play("请69号" + "张三" + ",到" + "体检一号室检查");

            }
        });

        select();


    }

    public void select() {
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // 这里写需要重复执行的逻辑代码
                if (is_enpaly) {
                    Testxml();
                }

            }
        }, 2000, 3000);

//        Testxml();
    }

    public void Testxml() {
        lineList.clear();
//        try {
//            List<Person> ps = sax_XML();
//            LogUtils.e(ps.size());
//            for (int i = 0; i <ps.size(); i++) {
//                Person p = ps.get(i);
//                Log.e("AA", p.getName() +"id="+p.getId()+",age="+p.getId() );
//            }
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }


        try {
            List<InfoBean> ps = sax_XMLTest();
            Collections.sort(ps);
            for (int i = 0; i < ps.size(); i++) {
                InfoBean p = ps.get(i);
//              LogUtils.e(p.getQueue_status());
                if (p.getQueue_status().equals("5")) {//等待就诊

                    lineList.add(p.getName());
                } else if (p.getQueue_status().equals("2")) {   //正在就诊
                    String output = p.getName().replaceAll("\\d", ""); // 使用 replaceAll() 函数将所有数字替换为空字符串
                    now_name = output;
                    now_number = p.getQueue_order()+"";
                    queue_id = p.getQueue_id();

                } else if (p.getQueue_status().equals("7")) {   //过号
                    guohao_list.add(p);
                }

            }


            is_data = true;
            Message msg = new Message();
            msg.what = 3;  //消息(一个整型值)
            mHandler.sendMessage(msg);// 每隔1秒发送一个msg给mHandler
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void play(String text) {
        if (null == mTts) {
            // 创建单例失败，与 21001 错误为同样原因，参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
            this.showTip("创建对象失败，请确认 libmsc.so 放置正确，\n 且有调用 createUtility 进行初始化");
            return;
        }
        // 设置参数
        setParam();
        int code = mTts.startSpeaking(text, mTtsListener);
        if (code != ErrorCode.SUCCESS) {
            showTip("语音合成失败,错误码: " + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");
        }
    }

    private void initRightTopView() {
        Date dt = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        txt_day.setText(sdf.format(dt));
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);
        String weekChinese = "";
        switch (weekday) {
            case 1:
                weekChinese = "日";
                break;
            case 2:
                weekChinese = "一";
                break;
            case 3:
                weekChinese = "二";
                break;
            case 4:
                weekChinese = "三";
                break;
            case 5:
                weekChinese = "四";
                break;
            case 6:
                weekChinese = "五";
                break;
            case 7:
                weekChinese = "六";
                break;
        }
        tvWeek.setText("星期" + weekChinese);
        new TimeThread().start();
    }

    /**
     * 实时获取时间
     */
    class TimeThread extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 1;  //消息(一个整型值)
                    mHandler.sendMessage(msg);// 每隔1秒发送一个msg给mHandler
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (isFinishing()) {
                        return;
                    }
                    long sysTime = System.currentTimeMillis();//获取系统时间
                    CharSequence sysTimeStr = DateFormat.format("HH:mm:ss", sysTime);//时间显示格式
                    tvTime.setText(sysTimeStr); //更新时间

                    Date dt = new Date(sysTime);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                    txt_day.setText(sdf.format(dt));

                    if (sysTimeStr.toString().equals("00:00")) {


                    }
                    break;

                case 2:
//                    txt_result.setText("结果显示：\n" + result);
                    Toast.makeText(MainActivity.this, "号码归属地查询成功", Toast.LENGTH_SHORT).show();
                    Log.e("号码归属地查询成功:", result + "");
                    break;

                case 3:
                    now_userName.setText(now_name);
                    now_userNumber.setText(now_number);

                    if (!queue_id.equals("") && !queue_id.equals(old_queue_id)) {


                        recyclerView.setAdapter(myAdapter);
                        linelist_lsv.setLines(lineList);
                        play("请" + now_number + "号" + now_name + ",到" + "体检一号室检查");
                    }


                    break;

                default:
                    break;

            }
        }
    };


    //定义一个获取号码归属地的方法：
    public void getland() {
        result = "";
        SoapObject soapObject = new SoapObject(AddressnameSpace, Addressmethod);
        soapObject.addProperty("mobileCode", "15633867446");
        soapObject.addProperty("userid", "02d6121c83d74048bc294a3455a01297");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut = soapObject;
        envelope.dotNet = true;
        envelope.setOutputSoapObject(soapObject);
        HttpTransportSE httpTransportSE = new HttpTransportSE(Addressurl);
        try {
            httpTransportSE.call(AddresssoapAction, envelope);

            LogUtils.e("调用WebService服务成功");
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("调用WebService服务失败");
        }

        //获得服务返回的数据,并且开始解析
        SoapObject object = (SoapObject) envelope.bodyIn;//System.out.println("获得服务数据");
        result = object.getProperty(0).toString();//System.out.println("获取信息完毕,向主线程发信息");
        mHandler.sendEmptyMessage(2);

    }


    public List<Person> sax_XML() throws Exception {
        //通过类加载器获取路径，再以输入流的方式放入解析器。
        InputStream is = MainActivity.class.getClassLoader().getResourceAsStream("person.xml");
        Log.e("----------", "is" + is);
        SAXForHandler handler = new SAXForHandler();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser saxParser = spf.newSAXParser();
        //使用SAXParser
        // saxParser.parse(is, handler);
        //使用xmlReader
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(is));
        List<Person> list = handler.getPersons();
        is.close();
        return list;
    }

    public List<InfoBean> sax_XMLTest() throws Exception {
        //通过类加载器获取路径，再以输入流的方式放入解析器。
        InputStream is = MainActivity.class.getClassLoader().getResourceAsStream("test.xml");
        Log.e("----------", "is" + is);
        SAXInfoData handler = new SAXInfoData();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser saxParser = spf.newSAXParser();
        //使用SAXParser
        // saxParser.parse(is, handler);
        //使用xmlReader
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(is));
//        reader.parse(new InputSource(new StringReader(xmlStr)));/
        List<InfoBean> list = handler.getInfoss();
        is.close();
        return list;
    }


    public void xunfeiinit() {
        // 初始化合成对象
        mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);

        // 云端发音人名称列表
        cloudVoicersEntries = getResources().getStringArray(R.array.voicer_cloud_entries);
        cloudVoicersValue = getResources().getStringArray(R.array.voicer_cloud_values);

        // 本地发音人名称列表
        localVoicersEntries = getResources().getStringArray(R.array.voicer_local_entries);
        localVoicersValue = getResources().getStringArray(R.array.voicer_local_values);

        // 增强版发音人名称列表
        xttsVoicersEntries = getResources().getStringArray(R.array.voicer_xtts_entries);
        xttsVoicersValue = getResources().getStringArray(R.array.voicer_xtts_values);

        mSharedPreferences = getSharedPreferences(TtsSettings.PREFER_NAME, Activity.MODE_PRIVATE);
    }

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d("---", "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败,错误码：" + code + ",请点击网址https://www.xfyun.cn/document/error-code查询解决方案");

            } else {
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };

    private void showTip(final String str) {

        LogUtils.e(str);

    }

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
            is_enpaly = false;
            //showTip("开始播放");
            Log.d("讯飞", "开始播放：" + System.currentTimeMillis());
        }

        @Override
        public void onSpeakPaused() {
            showTip("暂停播放");
        }

        @Override
        public void onSpeakResumed() {
            showTip("继续播放");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
            // 合成进度
            mPercentForBuffering = percent;
            showTip(String.format(getString(R.string.tts_toast_format),
                    mPercentForBuffering, mPercentForPlaying));
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
            mPercentForPlaying = percent;
            showTip(String.format(getString(R.string.tts_toast_format),
                    mPercentForBuffering, mPercentForPlaying));
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                is_enpaly = true;
                old_queue_id=queue_id;
//                Testxml();
                showTip("播放完成");
            } else {
                showTip(error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            if (SpeechEvent.EVENT_SESSION_ID == eventType) {
                String sid = obj.getString(SpeechEvent.KEY_EVENT_AUDIO_URL);
                Log.d("讯飞", "session id =" + sid);
            }

            //实时音频流输出参考
			/*if (SpeechEvent.EVENT_TTS_BUFFER == eventType) {
				byte[] buf = obj.getByteArray(SpeechEvent.KEY_EVENT_TTS_BUFFER);
				Log.e("MscSpeechLog", "buf is =" + buf);
			}*/
        }
    };

    /**
     * 参数设置
     */
    private void setParam() {
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        //设置合成
        if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
            //设置使用云端引擎
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            //设置发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicerCloud);

        } else if (mEngineType.equals(SpeechConstant.TYPE_LOCAL)) {
            //设置使用本地引擎
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            //设置发音人资源路径
            mTts.setParameter(ResourceUtil.TTS_RES_PATH, getResourcePath());
            //设置发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicerLocal);
        } else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_XTTS);
            //设置发音人资源路径
            mTts.setParameter(ResourceUtil.TTS_RES_PATH, getResourcePath());
            //设置发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicerXtts);
        }
        //mTts.setParameter(SpeechConstant.TTS_DATA_NOTIFY,"1");//支持实时音频流抛出，仅在synthesizeToUri条件下支持
        //设置合成语速
        mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", "50"));
        //设置合成音调
        mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50"));
        //设置合成音量
        mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "50"));
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3"));
        //	mTts.setParameter(SpeechConstant.STREAM_TYPE, AudioManager.STREAM_MUSIC+"");

        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH,
                getExternalFilesDir("msc").getAbsolutePath() + "/tts.pcm");


    }

    //获取发音人资源路径
    private String getResourcePath() {
        StringBuffer tempBuffer = new StringBuffer();
        String type = "tts";
        if (mEngineType.equals(SpeechConstant.TYPE_XTTS)) {
            type = "xtts";
        }
        //合成通用资源
        tempBuffer.append(ResourceUtil.generateResourcePath(this, ResourceUtil.RESOURCE_TYPE.assets, type + "/common.jet"));
        tempBuffer.append(";");
        //发音人资源
        if (mEngineType.equals(SpeechConstant.TYPE_XTTS)) {
            tempBuffer.append(ResourceUtil.generateResourcePath(this, ResourceUtil.RESOURCE_TYPE.assets, type + "/" + TtsDemo.voicerXtts + ".jet"));
        } else {
            tempBuffer.append(ResourceUtil.generateResourcePath(this, ResourceUtil.RESOURCE_TYPE.assets, type + "/" + TtsDemo.voicerLocal + ".jet"));
        }

        return tempBuffer.toString();
    }

    @Override
    protected void onDestroy() {
        if (null != mTts) {
            mTts.stopSpeaking();
            // 退出时释放连接
            mTts.destroy();
        }
        super.onDestroy();
    }

    /**
     * 设置当前屏幕方向为横屏
     */
    private void setHorizontalScreen(Activity activity) {
        if (activity.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    /**
     * 设置当前屏幕方向为竖屏
     */
    private void setVerticalScreen(Activity activity) {
        if (activity.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    // 语音合成对象
    private SpeechSynthesizer mTts;
    // 默认云端发音人
    public static String voicerCloud = "xiaoyan";
    // 默认本地发音人
    public static String voicerLocal = "xiaoyan";

    public static String voicerXtts = "xiaoyan";
    // 云端发音人列表
    private String[] cloudVoicersEntries;
    private String[] cloudVoicersValue;

    // 本地发音人列表
    private String[] localVoicersEntries;
    private String[] localVoicersValue;

    // 增强版发音人列表
    private String[] xttsVoicersEntries;
    private String[] xttsVoicersValue;

    //缓冲进度
    private int mPercentForBuffering = 0;
    //播放进度
    private int mPercentForPlaying = 0;

    // 云端/本地选择按钮
    private RadioGroup mRadioGroup;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_LOCAL;

    private Toast mToast;
    private SharedPreferences mSharedPreferences;

}
